package vn.lumi.smarthome.ui;

import java.util.ArrayList;
import java.util.Calendar;

import vn.lumi.smarthome.LumiHome;
import vn.lumi.smarthome.R;
import vn.lumi.smarthome.io.database.TBL_Device;
import vn.lumi.smarthome.io.model.Device;
import vn.lumi.smarthome.io.model.Scene;
import vn.lumi.smarthome.io.model.Time;
import vn.lumi.smarthome.load.DeviceListLoader;
import vn.lumi.smarthome.ulti.LogUltis;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.app.TimePickerDialog;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.Loader;
import android.view.ContextThemeWrapper;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.ToggleButton;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockFragmentActivity;

public abstract class AbstractSceneActivity extends SherlockFragmentActivity
		implements LoaderCallbacks<Device[]>, OnClickListener {

	protected static final String TAG = "AbstractSceneActivity";

	protected ListView mListDevices;
	protected ToggleButton tgbSchedule;
	protected Button mbtnTest;
	protected ImageView imv_picker_time;
	protected EditText medtName;
	protected ProgressDialog dialog;
	protected TextView tvPickertime;

	protected int mOldHour = 0;
	protected int mOldMinute = 0;
	protected int mCurrentHour = 0;
	protected int mCurrentMinute = 0;

	protected int mRoomID = 0;
	protected int mFloorID = 0;
	protected int mSceneID = 0;

	protected Device[] mOldDevices = null;
	protected Device[] mNewDevices = null;
	protected String oldSceneName = "";
	protected String newSceneName = "";

	private TextView tvSaveScene, tvCreatScene;

	protected int oldSceneMode = Scene.SCENE_MODE_NORMAL;

	public static final String EXTRA_FLOOR_ID = "floor_id";
	public static final String EXTRA_ROOM_ID = "room_id";
	public static final String EXTRA_SCENE_ID = "scene_id";
	public static final String EXTRA_SCENE_NAME = "scene_name";
	public static final String EXTRA_SCENE_MODE = "scene_schedule";
	public static final String EXTRA_SCENE_HOUR = "scene_hour";
	public static final String EXTRA_SCENE_MINUTE = "scene_minute";

	public static final String EXTRA_TYPE = "extra_type";
	public static final int TYPE_CREATE = 0;
	public static final int TYPE_EDIT = 1;

	protected DeviceListAdapter mDeviceListAdapter;

	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		setContentView(R.layout.activity_addscene);
		init_view();
		startLoadDeviceList(this);
		setupActionbar();
	}

	/**
	 * Set callback: Ok is clicked, Cancle is clicked, Test is clicked
	 */
	public abstract void saveScene();

	/**
	 * Set callback: Ok is clicked, Cancle is clicked, Test is clicked
	 */
	// public abstract void initCallback();

	private void init_view() {
		mListDevices = (ListView) findViewById(R.id.activity_addscene_list_device);
		tvPickertime = (TextViewCustom) findViewById(R.id.activity_addscene_tv_picker_time);
		mbtnTest = (Button) findViewById(R.id.activity_addscene_btn_test);
		medtName = (EditText) findViewById(R.id.activity_addscene_edt_name);
		imv_picker_time = (ImageView) findViewById(R.id.activity_addscene_picker_time);
		imv_picker_time.setOnClickListener(this);
		tgbSchedule = (ToggleButton) findViewById(R.id.activity_addscene_tgb_schedule);
		if (oldSceneMode == Scene.SCENE_MODE_AUTO) {
			tgbSchedule.setBackgroundResource(R.drawable.img_tickon);
			tgbSchedule.setChecked(true);
			tvPickertime.setText(padding_str(mOldHour)+ ":" + padding_str(mOldMinute));
		} else if (oldSceneMode == Scene.SCENE_MODE_NORMAL) {
			tgbSchedule.setBackgroundResource(R.drawable.img_tickoff);
			tgbSchedule.setChecked(false);
			tvPickertime.setText("");
		}
		mbtnTest.setOnClickListener(this);
		tgbSchedule
				.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

					@Override
					public void onCheckedChanged(CompoundButton buttonView,
							boolean isChecked) {
						// TODO Auto-generated method stub
						if (isChecked) {
							oldSceneMode = Scene.SCENE_MODE_AUTO;
							buttonView
									.setBackgroundResource(R.drawable.img_tickon);
							tvPickertime.setText(padding_str(getTimeSytem()
									.getHour())
									+ ":"
									+ padding_str(getTimeSytem().getMinute()));
							mCurrentHour = getTimeSytem().getHour();
							mCurrentMinute = getTimeSytem().getMinute();
						} else {
							oldSceneMode = Scene.SCENE_MODE_NORMAL;
							buttonView
									.setBackgroundResource(R.drawable.img_tickoff);
							tvPickertime.setText("");
						}
					}
				});

		medtName.setText(this.oldSceneName);
	}

	public abstract void startLoadDeviceList(
			LoaderCallbacks<Device[]> loaderCallback);

	private void setupActionbar() {
		ActionBar actionbar = getSupportActionBar();
		actionbar.setCustomView(R.layout.actionbar_setting_activity);
		actionbar.setDisplayShowHomeEnabled(false);
		actionbar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
		actionbar.setDisplayShowHomeEnabled(false);
		actionbar.setDisplayShowTitleEnabled(false);
		tvSaveScene = (TextView) findViewById(R.id.actionbar_setting_activity_logout);
		tvSaveScene.setText("Lưu lại");
		tvSaveScene.setTextSize(17);
		tvSaveScene.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (medtName.getText().toString().length() == 0) {
					// Thong bao chua dat ten canh
					showCustomDialog(R.string.txt_error,
							R.string.txt_scene_name_empty);
					return;
				}
				boolean isSceneEmpty = true;
				for (int i = 0; i < mDeviceListAdapter.getDevices().length; i++) {
					if (mDeviceListAdapter.getDevices()[i].isSelected()) {
						isSceneEmpty = false;
						break;
					}
				}
				if (isSceneEmpty == true) {
					showCustomDialog(R.string.txt_error,
							R.string.txt_empty_scene);
					return;
				}
				saveScene();
			}
		});
		tvCreatScene = (TextView) findViewById(R.id.actionbar_setting_activity_set);
		tvCreatScene.setText("Tạo cảnh");
		tvCreatScene.setTextSize(17);
	}

	@Override
	public Loader<Device[]> onCreateLoader(int arg0, Bundle bundle) {
		Loader<Device[]> loader = null;
		int mType = bundle.getInt(EXTRA_TYPE);

		if (mType == TYPE_CREATE) {
			loader = new DeviceListLoader(getApplicationContext(),
					DeviceListLoader.TYPE.CREATE, mRoomID);
		} else if (mType == TYPE_EDIT) {
			loader = new DeviceListLoader(getApplicationContext(),
					DeviceListLoader.TYPE.EDIT, mRoomID, mSceneID);
		}
		return loader;
	}

	@Override
	public void onLoadFinished(Loader<Device[]> arg0, Device[] devices) {
		for (int i = 0; i < devices.length; i++) {

			LogUltis.i(TAG, "DeviceName=" + devices[i].getName());
			LogUltis.i(TAG, "DeviceType=" + devices[i].getType_id());
			LogUltis.i(TAG, "DeviceState="
					+ devices[i].getDeviceState().getValue());
		}
		mOldDevices = new Device[devices.length];
		for (int i = 0; i < devices.length; i++) {
			mOldDevices[i] = new Device(devices[i]);
		}
		mDeviceListAdapter = new DeviceListAdapter(this, devices);
		mListDevices.setAdapter(mDeviceListAdapter);
	}

	@Override
	public void onLoaderReset(Loader<Device[]> arg0) {

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.activity_addscene_btn_test:
			boolean isSceneEmpty1 = true;
			for (int i = 0; i < mDeviceListAdapter.getDevices().length; i++) {
				if (mDeviceListAdapter.getDevices()[i].isSelected()) {
					isSceneEmpty1 = false;
					break;
				}
			}
			if (isSceneEmpty1 == true) {
				// displaySceneEmpty();
				showCustomDialog(R.string.txt_error, R.string.txt_empty_scene);
				return;
			}
			Device[] devices = mDeviceListAdapter.getDevices();
			for (int i = 0; i < devices.length; i++) {
				LogUltis.i(TAG, "Name=[" + devices[i].getName()
						+ "] vs Value=["
						+ devices[i].getDeviceState().getValue() + "]");
			}
			TestScene(devices);
			break;
		case R.id.activity_addscene_picker_time:
			// Hien thi chon thoi gian o day
			if (tgbSchedule.isChecked()) {
				TimepickDialog(getApplicationContext(), mCurrentHour,
						mCurrentMinute);
			}

			break;
		case R.id.activity_addscene_tv_picker_time:
			if (tgbSchedule.isChecked()) {
				TimepickDialog(getApplicationContext(), mCurrentHour,
						mCurrentMinute);
			}
			break;
		default:
			break;
		}
	}

	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		super.onBackPressed();
		finish();
	}

	private void TestScene(Device[] devices) {
		ArrayList<Device> normalDevices = new ArrayList<Device>();
		ArrayList<Device> RGBs = new ArrayList<Device>();
		for (int i = 0; i < devices.length; i++) {
			if (devices[i].isSelected()) {
				if (devices[i].getType_id() == Device.DEVICE_TYPE_RGB)
					RGBs.add(devices[i]);
				else
					normalDevices.add(devices[i]);
			}
		}
		// Control normal devices
		ContentValues values = new ContentValues();
		if (normalDevices.size() != 0) {
			int[] deviceID = new int[normalDevices.size()];
			int[] stateValue = new int[normalDevices.size()];
			int[] stateID = new int[normalDevices.size()];
			for (int i = 0; i < normalDevices.size(); i++) {
				deviceID[i] = normalDevices.get(i).getId();
				stateValue[i] = normalDevices.get(i).getDeviceState()
						.getValue();
				stateID[i] = normalDevices.get(i).getState_id();
			}
			values.put("DeviceID", convertIntArrayToString(deviceID));
			values.put("DeviceStateValue", convertIntArrayToString(stateValue));
			values.put("StateID", convertIntArrayToString(stateID));
			getApplicationContext().getContentResolver().update(
					TBL_Device.CONTENT_URI_CONTROL_NORMAL_DEVICE, values, null,
					null);

		}
		// Control RGB
		if (RGBs.size() != 0) {
			values.clear();
			int[] deviceID = new int[RGBs.size()];
			int[] stateValue = new int[RGBs.size()];
			int[] stateID = new int[RGBs.size()];
			for (int i = 0; i < RGBs.size(); i++) {
				deviceID[i] = RGBs.get(i).getId();
				stateValue[i] = RGBs.get(i).getDeviceState().getRGB();
				stateID[i] = RGBs.get(i).getState_id();
			}
			values.put("DeviceID", convertIntArrayToString(deviceID));
			values.put("DeviceStateValue", convertIntArrayToString(stateValue));
			values.put("StateID", convertIntArrayToString(stateID));
			getApplicationContext().getContentResolver().update(
					TBL_Device.CONTENT_URI_CONTROL_RGB, values, null, null);
		}

	}

	public static String convertIntArrayToString(int[] data) {
		String result = "";
		for (int i = 0; i < data.length; i++) {
			result += String.valueOf(data[i]) + ",";
		}
		return result;

	}

	public String convertIntArrayToString(Integer[] data) {
		// TODO Auto-generated method stub
		String result = "";
		for (int i = 0; i < data.length; i++) {
			result += String.valueOf(data[i]) + ",";
		}
		return result;
	}

	public static int[] convertStringToIntArray(String str) {
		if (str == "")
			return null;
		String[] array = str.split(",");
		int[] result = new int[array.length];
		for (int i = 0; i < array.length; i++) {
			result[i] = Integer.parseInt(array[i]);
		}
		return result;
	}

	public void showCustomDialog(int title, int message) {
		AlertDialog.Builder ErrorDialog = new AlertDialog.Builder(
				new ContextThemeWrapper(this, R.style.AlertDialogCustom));

		ChangeFont changeFont = new ChangeFont(this);
		TextView tvTitle = new TextView(this);
		tvTitle = changeFont.changeFontTextView(tvTitle, title,
				LumiHome.fontBold, LumiHome.sizeTittle, Gravity.CENTER,
				getResources().getColor(R.color.green));
		ErrorDialog.setCustomTitle(tvTitle);
		ErrorDialog.setMessage(message);
		ErrorDialog.setNegativeButton(R.string.glb_txt_return,
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.cancel();
					}
				});
		AlertDialog alertErrorDialog = ErrorDialog.create();
		alertErrorDialog.show();
		alertErrorDialog.getWindow().getAttributes();
		TextView tvMessage = (TextView) alertErrorDialog
				.findViewById(android.R.id.message);
		tvMessage = changeFont.changeFontTextView(tvMessage, message,
				LumiHome.font, LumiHome.sizeContent, Gravity.NO_GRAVITY,
				getResources().getColor(R.color.greenLight));

		Button btn1 = alertErrorDialog
				.getButton(DialogInterface.BUTTON_NEGATIVE);
		btn1.setTypeface(Typeface.createFromAsset(getAssets(),
				LumiHome.fontBold));
		btn1.setTextColor(getResources().getColor(R.color.greenActionbar));
		btn1.setTextSize(LumiHome.sizeButton);
	}

	private void TimepickDialog(Context cons, int curHours, int curMinutes) {
		View view = getLayoutInflater()
				.inflate(R.layout.dialog_wheeltime, null);

		// hours wheel
		final TimePicker timePicker = (TimePicker) view
				.findViewById(R.id.timePicker);
		timePicker.setIs24HourView(true);

		final Button save = (ButtonCustom) view
				.findViewById(R.id.dialog_wheeltime_save);
		final Button cancel = (ButtonCustom) view
				.findViewById(R.id.dialog_wheeltime_cancel);

		AlertDialog.Builder alert = new AlertDialog.Builder(
				new ContextThemeWrapper(this, R.style.AlertDialogCustom));
		TextView title = new TextView(this);
		ChangeFont fontTitle = new ChangeFont(getApplicationContext());
		title = fontTitle.changeFontTextView(title, R.string.txt_picker_time,
				LumiHome.font, LumiHome.sizeTittle, Gravity.CENTER,
				getResources().getColor(R.color.green));
		alert.setCustomTitle(title);

		alert.setView(view);
		alert.setCancelable(false);

		final AlertDialog dialog = alert.create();
		dialog.show();

		save.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				mCurrentHour = timePicker.getCurrentHour();
				mCurrentMinute = timePicker.getCurrentMinute();
				tvPickertime.setText(padding_str(mCurrentHour) + ":"
						+ padding_str(mCurrentMinute));
				dialog.cancel();
				return;
			}
		});
		cancel.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				dialog.cancel();
				return;
			}
		});

		// set time
		timePicker.setCurrentHour(curHours);
		timePicker.setCurrentMinute(curMinutes);

	}

	public static Time getTimeSytem() {
		Calendar c = Calendar.getInstance();
		Time timeSystem = new Time(c.get(Calendar.HOUR_OF_DAY),
				c.get(Calendar.MINUTE));
		return timeSystem;
	}

	public static String padding_str(int c) {
		if (c >= 10)
			return String.valueOf(c);
		else
			return "0" + String.valueOf(c);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#finish()
	 */
	@Override
	public void finish() {
		// TODO Auto-generated method stub
		Intent intentMainActivity = new Intent();
		intentMainActivity.putExtra("Scene", true);
		setResult(RESULT_OK, intentMainActivity);
		super.finish();
	}
}
